package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.StatusConstant;
import com.sky.dto.CategoryDTO;
import com.sky.dto.CategoryPageQueryDTO;
import com.sky.entity.Category;
import com.sky.exception.BusinessException;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageBean;
import com.sky.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

// 分类管理
@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    // 分页查询
    @Override
    public PageBean<Category> findByPage(CategoryPageQueryDTO dto) {
        //1. 开启分页
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        //2. 条件查询
        List<Category> list = categoryMapper.findList(dto);
        Page<Category> page = (Page<Category>) list;
        //3. 返回分页
        return new PageBean<>(page.getTotal(),page.getResult());
    }

    // 新增分类
    @Override
    public void save(Category category) {
        //1. 补齐参数
        category.setStatus(StatusConstant.ENABLE);// 启用（上架）
        //2. 调用mapper保存
        categoryMapper.save(category);
    }

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    // 删除分类
    @Override
    public void deleteById(Long id) {
        //1. 先查询该分类下是否还有菜品，如果有直接报错
        Integer dishCount = dishMapper.countByCategoryId(id);
        if (dishCount>0) {
            throw new BusinessException("该分类下还有菜品，无法删除");
        }
        //2. 再查询该分类下是否还有套餐，如果有直接报错
        Integer setmealCount = setmealMapper.countByCategoryId(id);
        if (setmealCount>0) {
            throw new BusinessException("该分类下还有套餐，无法删除");
        }
        //3. 执行分类删除
        categoryMapper.deleteById(id);
    }
    //修改
    @Override
    public void update(Category category) {
        categoryMapper.update(category);
    }

    // 根据type查询分类列表
    @Override
    public List<Category> findByType(Integer type) {
        //1. 将type封装到dto
        CategoryPageQueryDTO dto = new CategoryPageQueryDTO();
        dto.setType(type);
        //2. 调用mapper查询并返回
        return categoryMapper.findList(dto);
    }

    // 查询首页分类列表
    @Override
    public List<Category> findByStatusAndType(Integer type) {
        //1. 封装dto
        CategoryDTO dto = new CategoryDTO();
        dto.setType(type);
        dto.setStatus(1);// 启用
        //2. 调用mapper查询并返回
        return categoryMapper.findByStatusAndType(dto);
    }
}
